<?php


namespace app\admin\controller;


use app\common\traits\Jump;
use think\App;
use think\Container;
use think\Request;

abstract class BaseController
{
    use Jump;

    /**
     * @var App
     */
    protected $app;

    /**
     * @var Request
     */
    protected $request;

    protected $vars = [];

    public function __construct()
    {
        $this->app = Container::get('app');
        $this->request = $this->app->request;
    }


    protected function assign($name, $value = null)
    {
        if (is_array($name)) {
            $this->vars = array_merge($this->data, $name);
        } else {
            $this->vars[$name] = $value;
        }
    }


    /**
     * 验证数据
     * @access protected
     * @param  array        $data     数据
     * @param  string|array $validate 验证器名或者验证规则数组
     * @param  string       $scene    场景
     * @param  bool         $batch    是否批量验证
     * @param  mixed        $callback 回调方法（闭包）
     * @return array|string|true
     */
    protected function validate($data, $validate, $scene = null, $batch = false, $callback = null)
    {
        if (is_array($validate)) {
            $v = $this->app->validate();
            $v->rule($validate);
        } else {
            $v = $this->app->validate($validate);
        }
        if (!is_null($scene)) {
            $v->scene($scene);
        }

        // 是否批量验证
        if ($batch) {
            $v->batch(true);
        }

        if ($callback && is_callable($callback)) {
            call_user_func_array($callback, [$v, &$data]);
        }

        if (!$v->check($data)) {
            return $v->getError();
        }

        return true;
    }

}
